#!/usr/bin/ruby

require 'drb/drb'
require 'thread'

READ_BUF_SIZE = 1024

class Svr
  attr_accessor :w
  
  def initialize
    @work_threads = {}
  end
  
  def bind(clt)
    t = working_loop(clt,*IO.pipe)
    @work_threads[clt.name] = t
    #如果没有延时则返回的t[:w]为nil
    sleep 0.1
    t[:w]
  end
  
  #删除已死的work_thread
  def clear_dead_thread
    @work_threads.delete_if {|k,t|!t.alive?}
  end
  
  def working_loop(clt,r,w)
    Thread.new(clt,r,w) do |clt,r,w|
      t = Thread.current
      t[:clt] = clt
      t[:w] = w
      clt.w.write("hello #{clt}\n")
      loop do
        begin
          sleep 0.1
          str = r.read_nonblock READ_BUF_SIZE
          str.chop!.force_encoding("utf-8")
          if str =~ /quit/i
            clt.w.write("byebye...\n")
            break
          end
          #puts "recv from #{clt} : #{str}:#{str.encoding}"
          clt.w.write(str.reverse + " #{Time.now}\n")
        rescue IO::EAGAINWaitReadable =>e
          nil
        end
      end
    end
  end
  
  private :working_loop
end

uri = "druby://localhost:8087"

class TimeSvr
	def get_current_time
		return Time.now
	end
end

#obj = TimeSvr.new
obj = Svr.new
DRb.start_service(uri,obj)
DRb.thread.join
